package com.CommunityHub.kiana.controller;
import com.CommunityHub.kiana.po.HouseInfo;
import com.CommunityHub.kiana.po.MemberDetail;
import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.po.VenueInfo;
import com.CommunityHub.kiana.service.AdminService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import static com.CommunityHub.kiana.controller.FIleUIploadController.BASE_DIR;

@WebServlet("/admin/*")
public class AdminServlet extends HttpServlet {
    private AdminService adminService = new AdminService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String action = request.getPathInfo();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("../login.jsp");
            return;
        }

        try {
            switch (action) {
                case "/members":
                    listMembers(request, response);
                    break;
                case "/houses":
                    listHouses(request, response);
                    break;
                case "/venues":
                    listVenues(request, response);
                    break;
                case "/users":
                    listUsers(request, response);
                    break;
                case "/profile":
                    showProfile(request, response);
                    break;
                case "/logout":
                    response.sendRedirect("../login.jsp");
                    break;
                default:
                    response.sendRedirect("../adminHome.jsp");
                    break;
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        String action = request.getPathInfo();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("../login.jsp");
            return;
        }

        try {
            switch (action) {
                case "/updateProfile":
                    updateProfile(request, response);
                    break;
                case "/addMember":
                    addMember(request, response);
                    break;
                case "/updateMember":
                    updateMember(request, response);
                    break;
                case "/deleteMember":
                    deleteMember(request, response);
                    break;
                case "/addHouse":
                    addHouse(request, response);
                    break;
                case "/updateHouse":
                    updateHouse(request, response);
                    break;
                case "/addVenue":
                    addVenue(request, response);
                    break;
                case "/updateVenue":
                    updateVenue(request, response);
                    break;
                case "/deleteVenue":
                    deleteVenue(request, response);
                    break;
                case "/updateUser":
                    updateUser(request, response);
                    break;
                case "/addUser":
                    addUser(request, response);
                    break;
                case "/deleteUser":
                    deleteUser(request, response);
                    break;
                default:
                    response.sendRedirect("../adminHome.jsp");
                    break;
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    private void listMembers(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        List<MemberDetail> members = adminService.getAllMembers();
        request.setAttribute("members", members);
        request.getRequestDispatcher("/admins/memberManagement.jsp").forward(request, response);
    }

    private void listHouses(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        List<HouseInfo> houses = adminService.getAllHouses();
        request.setAttribute("houses", houses);
        request.getRequestDispatcher("/admins/houseManagement.jsp").forward(request, response);
    }

    private void listVenues(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        List<VenueInfo> venues = adminService.getAllVenues();
        request.setAttribute("venues", venues);
        request.getRequestDispatcher("/admins/venueManagement.jsp").forward(request, response);
    }

    private void listUsers(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        List<User> users = adminService.getAllUsers();
        request.setAttribute("users", users);
        request.getRequestDispatcher("/admins/userManagement.jsp").forward(request, response);
    }

    private void showProfile(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        request.getRequestDispatcher("/admins/profile.jsp").forward(request, response);
    }

    private void updateProfile(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");

        User user = new User();
        user.setId(currentUser.getId());
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        user.setPhone(request.getParameter("phone"));
        user.setIdCard(request.getParameter("idCard"));
        user.setContactName(request.getParameter("contactName"));
        user.setContactPhone(request.getParameter("contactPhone"));

        // 保留其他字段不变
        user.setRole(currentUser.getRole());
        user.setSex(currentUser.getSex());
        user.setBirthData(currentUser.getBirthData());
        user.setMemberType(currentUser.getMemberType());
        user.setStatus(currentUser.getStatus());

        if (adminService.updateUser(user)) {
            session.setAttribute("user", adminService.login(user.getUsername(), user.getPassword()));
            request.setAttribute("success", "个人信息更新成功");
        } else {
            request.setAttribute("error", "个人信息更新失败");
        }
        request.getRequestDispatcher("/admins/profile.jsp").forward(request, response);
    }

    private void addMember(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        MemberDetail member = new MemberDetail();
        member.setMemberId(Integer.parseInt(request.getParameter("memberId")));
        member.setRealName(request.getParameter("realName"));
        member.setGender(request.getParameter("gender"));
        member.setBirthDate(java.sql.Date.valueOf(request.getParameter("birthDate")));
        member.setPhone(request.getParameter("phone"));
        member.setIdCard(request.getParameter("idCard"));
        member.setContactName(request.getParameter("contactName"));
        member.setContactPhone(request.getParameter("contactPhone"));
        member.setMemberType(request.getParameter("memberType"));
        member.setRemark(request.getParameter("remark"));

        if (adminService.addMember(member)) {
            request.setAttribute("success", "添加会员成功");
        } else {
            request.setAttribute("error", "添加会员失败");
        }
        listMembers(request, response);
    }

    private void updateMember(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        MemberDetail member = new MemberDetail();
        member.setMemberId(Integer.parseInt(request.getParameter("memberId")));
        member.setRealName(request.getParameter("realName"));
        member.setGender(request.getParameter("gender"));
        member.setBirthDate(java.sql.Date.valueOf(request.getParameter("birthDate")));
        member.setPhone(request.getParameter("phone"));
        member.setIdCard(request.getParameter("idCard"));
        member.setContactName(request.getParameter("contactName"));
        member.setContactPhone(request.getParameter("contactPhone"));
        member.setMemberType(request.getParameter("memberType"));
        member.setRemark(request.getParameter("remark"));

        if (adminService.updateMember(member)) {
            request.setAttribute("success", "更新会员信息成功");
        } else {
            request.setAttribute("error", "更新会员信息失败");
        }
        listMembers(request, response);
    }

    private void deleteMember(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        int memberId = Integer.parseInt(request.getParameter("memberId"));

        if (adminService.deleteMember(memberId)) {
            request.setAttribute("success", "删除会员成功");
        } else {
            request.setAttribute("error", "删除会员失败");
        }
        listMembers(request, response);
    }

    private void addHouse(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        HouseInfo house = new HouseInfo();
        FileItem imageFileItem = null; // 用于临时保存图片文件项
        String imageFileName = null; // 用于保存最终图片文件名

        try {
            // 创建文件上传处理器
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("jakarta.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 解析请求
            List<FileItem> items = upload.parseRequest(request);

            // 处理表单字段
            for (FileItem fileItem : items) {
                String fieldName = fileItem.getFieldName();

                if (fileItem.isFormField()) {
                    // 处理普通表单字段
                    switch (fieldName) {
                        case "houseName":
                            house.setHouseName(fileItem.getString("UTF-8"));
                            break;
                        case "buildingNumber":
                            house.setBuildingNumber(fileItem.getString("UTF-8"));
                            break;
                        case "unitNumber":
                            house.setUnitNumber(fileItem.getString("UTF-8"));
                            break;
                        case "roomNumber":
                            house.setRoomNumber(fileItem.getString("UTF-8"));
                            break;
                        case "area":
                            house.setArea(new BigDecimal(fileItem.getString("UTF-8")));
                            break;
                        case "price":
                            house.setPrice(new BigDecimal(fileItem.getString("UTF-8")));
                            break;
                        case "status":
                            house.setStatus(Integer.parseInt(fileItem.getString("UTF-8")));
                            break;
                        case "buyerId":
                            String buyerIdStr = fileItem.getString("UTF-8");
                            if (!buyerIdStr.isEmpty()) {
                                house.setBuyerId(Integer.parseInt(buyerIdStr));
                            }
                            break;
                    }
                } else {
                    // 处理文件上传字段
                    if (fileItem.getSize() > 0) { // 确保有文件上传
                        imageFileItem = fileItem; // 暂存文件项
                        imageFileName = UUID.randomUUID().toString() +
                                getFileExtension(fileItem.getName());
                    }
                }
            }

            // 先尝试添加房屋信息到数据库
            boolean addSuccess = adminService.addHouse(house);

            if (addSuccess) {
                // 只有在数据库操作成功后才保存图片
                if (imageFileItem != null) {
//                    String uploadPath = request.getServletContext().getRealPath("/pictures");
                    File uploadDir = new File(BASE_DIR);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    imageFileName = "pictures/"+imageFileName;
                    File file = new File(uploadDir, imageFileName);
                    imageFileItem.write(file);

                    // 更新数据库中的图片路径
                    house.setHouseImage(imageFileName);
                    adminService.updateHouseImage(house.getBuildingNumber(), house.getUnitNumber(), house.getRoomNumber(), house.getHouseImage());
                }


                request.setAttribute("success", "添加房屋信息成功");
            } else {
                request.setAttribute("error", "添加房屋信息失败");
            }

        } catch (NumberFormatException e) {
            request.setAttribute("error", "数值格式不正确: " + e.getMessage());
        } catch (SQLException e) {
            request.setAttribute("error", "数据库错误: " + e.getMessage());
        } catch (Exception e) {
            request.setAttribute("error", "系统错误: " + e.getMessage());
        } finally {
            listHouses(request, response);
        }
    }

    // 获取文件扩展名
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return ".png"; // 默认扩展名
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    private void updateHouse(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        int houseId = Integer.parseInt(request.getParameter("houseId"));
        int status = Integer.parseInt(request.getParameter("status"));
        double price = Double.parseDouble(request.getParameter("price"));

        Integer buyerId = null;
        HouseInfo house = new HouseInfo();
        house.setHouseId(houseId);
        house.setStatus(status);
        house.setPrice(BigDecimal.valueOf(price));
        if (status == 1) {
            buyerId = Integer.parseInt(request.getParameter("buyerId"));
        }

        if (adminService.updateHouseStatus(houseId, status, buyerId, price)) {
            request.setAttribute("success", "更新房屋状态成功");
        } else {
            request.setAttribute("error", "更新房屋状态失败");
        }
        listHouses(request, response);
    }

    private void addVenue(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        VenueInfo venue = new VenueInfo();
        venue.setVenueName(request.getParameter("venueName"));
        venue.setAddress(request.getParameter("address"));
        venue.setSpecialNote(request.getParameter("specialNote"));
        venue.setOpeningTime(java.sql.Time.valueOf(request.getParameter("openingTime") + ":00"));
        venue.setClosingTime(java.sql.Time.valueOf(request.getParameter("closingTime") + ":00"));
        venue.setContactPhone(request.getParameter("contactPhone"));
        venue.setUsageStatus(Integer.parseInt(request.getParameter("usageStatus")));
        venue.setLocation(request.getParameter("location"));
        venue.setSize(new java.math.BigDecimal(request.getParameter("size")));
        venue.setVenueType(request.getParameter("venueType"));
        String responsibleId = request.getParameter("responsibleId");
        venue.setResponsibleId(responsibleId.isEmpty() ? null : Integer.parseInt(responsibleId));
        venue.setChargeStandard(new java.math.BigDecimal(request.getParameter("chargeStandard")));
        venue.setPublishStatus(Integer.parseInt(request.getParameter("publishStatus")));

        if (adminService.addVenue(venue)) {
            request.setAttribute("success", "添加场馆成功");
        } else {
            request.setAttribute("error", "添加场馆失败");
        }
        listVenues(request, response);
    }

    private void updateVenue(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        VenueInfo venue = new VenueInfo();
        venue.setVenueId(Integer.parseInt(request.getParameter("venueId")));
        venue.setVenueName(request.getParameter("venueName"));
        venue.setAddress(request.getParameter("address"));
        venue.setSpecialNote(request.getParameter("specialNote"));
        venue.setOpeningTime(java.sql.Time.valueOf(request.getParameter("openingTime") + ":00"));
        venue.setClosingTime(java.sql.Time.valueOf(request.getParameter("closingTime") + ":00"));
        venue.setContactPhone(request.getParameter("contactPhone"));
        venue.setUsageStatus(Integer.parseInt(request.getParameter("usageStatus")));
        venue.setLocation(request.getParameter("location"));
        venue.setSize(new java.math.BigDecimal(request.getParameter("size")));
        venue.setVenueType(request.getParameter("venueType"));
        String responsibleId = request.getParameter("responsibleId");
        venue.setResponsibleId(responsibleId.isEmpty() ? null : Integer.parseInt(responsibleId));
        venue.setChargeStandard(new java.math.BigDecimal(request.getParameter("chargeStandard")));
        venue.setPublishStatus(Integer.parseInt(request.getParameter("publishStatus")));

        if (adminService.updateVenue(venue)) {
            request.setAttribute("success", "更新场馆信息成功");
        } else {
            request.setAttribute("error", "更新场馆信息失败");
        }
        listVenues(request, response);
    }

    private void deleteVenue(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        int venueId = Integer.parseInt(request.getParameter("venueId"));

        if (adminService.deleteVenue(venueId)) {
            request.setAttribute("success", "删除场馆成功");
        } else {
            request.setAttribute("error", "删除场馆失败");
        }
        listVenues(request, response);
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        User user = new User();
        user.setId(Integer.parseInt(request.getParameter("userId")));
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        user.setRole(request.getParameter("role"));
        user.setSex(request.getParameter("sex"));
        user.setBirthData(java.sql.Date.valueOf(request.getParameter("birthData")));
        user.setPhone(request.getParameter("phone"));
      //  user.setIdCard(request.getParameter("idCard"));
        user.setContactName(request.getParameter("contactName"));
        user.setContactPhone(request.getParameter("contactPhone"));
        user.setMemberType(request.getParameter("memberType"));
        user.setStatus(Integer.parseInt(request.getParameter("status")));

        if (adminService.updateUser(user)) {
            request.setAttribute("success", "更新用户信息成功");
        } else {
            request.setAttribute("error", "更新用户信息失败");
        }
        listUsers(request, response);
    }
    private void addUser(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {

        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        user.setRole(request.getParameter("role"));
        user.setSex(request.getParameter("sex"));
        user.setBirthData(java.sql.Date.valueOf(request.getParameter("birthData")));
        user.setPhone(request.getParameter("phone"));
        user.setIdCard(request.getParameter("idCard"));
        user.setContactName(request.getParameter("contactName"));
        user.setContactPhone(request.getParameter("contactPhone"));
        user.setMemberType(request.getParameter("memberType"));
        user.setStatus(Integer.parseInt(request.getParameter("status")));

        if (adminService.addUser(user)) {
            request.setAttribute("success", "用户添加成功");
        } else {
            request.setAttribute("error", "用户添加失败");
        }

        listUsers(request, response);
    }
    private void deleteUser(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        int userId = Integer.parseInt(request.getParameter("userId"));

        if (adminService.deleteUser(userId)) {
            request.setAttribute("success", "删除用户成功");
        } else {
            request.setAttribute("error", "删除用户失败");
        }
        listUsers(request, response);
    }

}